from gm.api import *
import numpy as np
import talib


def init(context):
    '''主程序初始化'''
    context.symbol = 'SZSE.300296'
    context.frequency = '1d'
    context.fields = 'open,high,low,close'
    context.volume = 200

    schedule(schedule_func=algo, date_rule='1d', time_rule='09:35:00')


def algo(context):
    now = context.now
    last_day = get_previous_trading_date('SZSE', now)
    data = history_n(symbol=context.symbol,
                     frequency=context.frequency,
                     count=35,
                     end_time=now,
                     fields=context.fields,
                     fill_missing='last',
                     adjust=ADJUST_PREV,
                     df=True,
                     )
    open = np.asarray((data['open'].values))
    high = np.asarray((data['high'].values))
    low = np.asarray((data['low'].values))
    close = np.asarray((data['close'].values))

    macd, _, _ = talib.MACD(close)
    macd = macd[-1]

    rsi = talib.RSI(close)
    rsi = rsi[-1]

    if rsi < 40:
        order_volume(symbol=context.symbol,
                     volume=context.volume,
                     side=PositionSide_Long,
                     order_type=OrderType_Market,
                     position_effect=PositionEffect_Open,
                     )
        print('买入', )
    elif rsi > 60:
        order_volume(symbol=context.symbol,
                     volume=context.volume,
                     side=PositionSide_Short,
                     order_type=OrderType_Market,
                     position_effect=PositionEffect_Close
                     )
        print('卖出')


# 查看最终的回测结果
def on_backtest_finished(context, indicator):
    print(indicator)


if __name__ == '__main__':
    run(
        strategy_id='a5299b24-8b44-11e9-a4d4-b499baf0193a',
        filename='程序5_10RSI3034策略.py',
        mode=MODE_BACKTEST,
        token='90be3f863b23ab3c1ef68d1f9b8dc06e4bebb30d',
        backtest_start_time='2014-01-01 09:00:00',
        backtest_end_time='2018-12-31 15:00:00',
        backtest_initial_cash=20000,
        backtest_adjust=ADJUST_PREV,
    )
